package controller;

import business.ebi.CommodityEBI;
import business.factory.BusinessFactory;
import entity.Commodity;
import entity.GoodsItem;
import entity.ShoppingCart;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "shoppingcart", urlPatterns = "/ShoppingCart")
public class ShoppingCartController extends HttpServlet {

    private final CommodityEBI ebi = BusinessFactory.getCommodityEBI();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String cId = req.getParameter("cId");
        Commodity commodity = null;
        try {
            commodity = ebi.search_id(cId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        Integer quality = Integer.valueOf(req.getParameter("quality"));
        GoodsItem goodsItem = new GoodsItem(commodity, quality);
        HttpSession session = req.getSession();
        ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute("shoppingcart");
        if (shoppingCart == null) {
            shoppingCart = new ShoppingCart();
            session.setAttribute("shoppingcart", shoppingCart);
        }
        shoppingCart.update(goodsItem);
        resp.sendRedirect(req.getContextPath() + "CommodityListController");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");
        String cId = req.getParameter("cId");
        ShoppingCart shoppingcart = (ShoppingCart) req.getSession().getAttribute("shoppingcart");
        shoppingcart.remove(cId);
        if (shoppingcart.getMap().isEmpty()) {
            resp.getWriter().write("<script language=javascript>alert('" + "购物车目前无商品,点击确定返回商品首页" + "');window.location='CommodityListController'</script>");
        } else {
            req.getRequestDispatcher("/ShoppingCar.jsp").forward(req, resp);
        }
    }
}
